package com.heatingcharge.service.unit.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.BeanValidator;
import com.heatingcharge.common.util.LevelUtil;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.dto.HeatSourcePlantDTO;
import com.heatingcharge.entity.unit.HeatChangeStation;
import com.heatingcharge.entity.unit.HeatCompany;
import com.heatingcharge.entity.unit.HeatSourcePlant;
import com.heatingcharge.mapper.unit.HeatChangeStationMapper;
import com.heatingcharge.mapper.unit.HeatCompanyMapper;
import com.heatingcharge.mapper.unit.HeatSourcePlantMapper;
import com.heatingcharge.param.HeatSourcePlantParam;
import com.heatingcharge.service.unit.IHeatSourcePlantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 热源  服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-07-12
 */
@Service
public class HeatSourcePlantServiceImpl extends ServiceImpl<HeatSourcePlantMapper, HeatSourcePlant> implements IHeatSourcePlantService {

    @Autowired
    HeatCompanyMapper heatCompanyMapper;

    @Autowired
    HeatChangeStationMapper heatChangeStationMapper;


    @Override
    public IPage<HeatSourcePlant> selectHeatSourcePlantPage(Page heatSourcePlantPage,HeatSourcePlantDTO heatSourcePlantDTO) {
        if (heatSourcePlantDTO.getCompanyId()!=0){
            HeatCompany heatCompany = heatCompanyMapper.selectById(heatSourcePlantDTO.getCompanyId());
            String level=LevelUtil.calculateLevel(heatCompany.getLevel(), heatCompany.getId());
            List<Integer> companyIds= heatCompanyMapper.selectList(
                    Wrappers.<HeatCompany>query().lambda().likeRight(HeatCompany::getLevel, level))
                    .stream().map(HeatCompany::getId).collect(Collectors.toList());
            companyIds.add(heatCompany.getId());
            heatSourcePlantDTO.setCompanyList(companyIds);
        }
        return baseMapper.selectHeatSourcePlantVo(heatSourcePlantPage,heatSourcePlantDTO);
    }

    @Override
    public List<HeatSourcePlant> selectAllHeatSourcePlant(HeatSourcePlantDTO heatSourcePlantDTO) {
        if (heatSourcePlantDTO.getCompanyId()!=0){
            HeatCompany heatCompany = heatCompanyMapper.selectById(heatSourcePlantDTO.getCompanyId());
            String level=LevelUtil.calculateLevel(heatCompany.getLevel(), heatCompany.getId());
            List<Integer> companyIds= heatCompanyMapper.selectList(
                    Wrappers.<HeatCompany>query().lambda().likeRight(HeatCompany::getLevel, level))
                    .stream().map(HeatCompany::getId).collect(Collectors.toList());
            companyIds.add(heatCompany.getId());
            heatSourcePlantDTO.setCompanyList(companyIds);
        }
        return baseMapper.selectHeatSourcePlantVo(heatSourcePlantDTO);
    }

    //新增
    @Override
    public boolean save(HeatSourcePlantParam heatSourcePlantParam) {
        //校验字段合法性
        BeanValidator.check(heatSourcePlantParam);
        //检验热力公司是否已经存在
        if (checkExist(heatSourcePlantParam.getCompanyId(),heatSourcePlantParam.getName(),null)){
            //热力公司已经存在
            throw new BaseException(ResponseCodeEnum.HEATSOURCEPLANT_EXIST.getMessage(),ResponseCodeEnum.HEATSOURCEPLANT_EXIST.getCode());
        }
        HeatSourcePlant heatSourcePlant=HeatSourcePlant.builder()
                .name(heatSourcePlantParam.getName())
                .companyId(heatSourcePlantParam.getCompanyId())
                .addr(heatSourcePlantParam.getAddr())
                .build();
        return baseMapper.insert(heatSourcePlant)>0;
    }

    /**
     * 同一热力公司下是否存在相同的热源厂
     * @param companyId
     * @param name
     * @param id
     * @return
     */
    private boolean checkExist(Integer companyId,String name, Integer id) {
        QueryWrapper<HeatSourcePlant> queryWrapper=new QueryWrapper<>();
        if (companyId!=null) {
            queryWrapper.eq("company_id",companyId);
        }
        queryWrapper.eq("name",name);
        if (id!=null){
            queryWrapper.ne("id",id);
        }
        return this.list(queryWrapper).size()>0;
    }

    //修改
    @Override
    public boolean update(HeatSourcePlantParam heatSourcePlantParam) {
        //校验字段合法性
        BeanValidator.check(heatSourcePlantParam);
        //检验热力公司是否已经存在
        if (checkExist(heatSourcePlantParam.getCompanyId(),heatSourcePlantParam.getName(),heatSourcePlantParam.getId())){
            //热力公司已经存在
            throw new BaseException(ResponseCodeEnum.HEATSOURCEPLANT_EXIST.getMessage(),ResponseCodeEnum.HEATSOURCEPLANT_EXIST.getCode());
        }
        HeatSourcePlant before=this.getById(heatSourcePlantParam.getId());
        if (ObjectUtil.isNull(before)){
            throw new BaseException(ResponseCodeEnum.HEATSOURCEPLANT_NON_EXIST.getMessage(),ResponseCodeEnum.HEATSOURCEPLANT_NON_EXIST.getCode());
        }
        HeatSourcePlant after=new HeatSourcePlant();
        BeanUtils.copyProperties(heatSourcePlantParam, after);

        return baseMapper.updateById(after)>0;
    }

    //删除
    @Override
    public boolean removeById(Serializable id) {
        // 热力公司层级删除
        List<Integer> idList = heatChangeStationMapper
                .selectList(Wrappers.<HeatChangeStation>query()
                        .lambda()
                        .eq(HeatChangeStation::getPlantId, id))
                .stream().map(HeatChangeStation::getId)
                .collect(Collectors.toList());
        //如果存在子热力公司  则不能删除
        if (idList.size()>0){
            throw new BaseException(ResponseCodeEnum.HEATSOURCEPLANT_HAS_CHILDREN.getMessage(),ResponseCodeEnum.HEATSOURCEPLANT_HAS_CHILDREN.getCode());
        }
        return super.removeById(id);
    }
}
